<?php

namespace app\models\auth_app\doudian;

use app\components\Func;
use Yii;
use app\models\AuthApp;

class AuthAppDoudianOrder extends AuthAppDoudian
{
    //评论回复
    public function messageReply(AuthAccount $authAccount,$authMessage,$content){
        if($authAccount->isDouyinCompany()){
            $url = self::DOUYIN_URL_SEND_MESSAGE_COMPANY;
        }else{
            $url = self::DOUYIN_URL_SEND_MESSAGE_COMMON;
        }
        $content = DouyinEmoji::inputContent($content);
        $query_arr = [
            'open_id'=>$authAccount->open_id,
            'access_token'=>$authAccount->token,
        ];
        $body_arr['to_user_id']=$authMessage->otherUser->open_id;
        $body_arr['content']=['text'=>$content];
        $body_arr['message_type']='text';
//        print_r($body_arr);exit;
        $body = json_encode($body_arr,JSON_UNESCAPED_UNICODE);
        $response = Func::postData(
            $url.'?'.http_build_query($query_arr),
            $body,5,
            ['Content-Type:application/json','Accept:application/json']);
        $result = self::checkResponse($response);
        $obj = new AuthMessage();
        $obj->auth_app_id = $this->id;
        $obj->auth_account_id = $authAccount->id;
        $obj->auth_uid = $authAccount->app_uid;
        $obj->other_uid = $authMessage->other_uid;
        $obj->is_send = 1;
        $obj->content_type = 1;
        $obj->content = json_encode(['message_type'=>'text','text'=>$content],JSON_UNESCAPED_UNICODE);
        $obj->ctime = time();
        if(!$obj->save()){
            throw new \Exception(json_encode($obj->getErrors()));
        }
        return $result;
    }
    //评论回复
    public function commentReply(AuthAccount $authAccount,AuthItem $authItem,$authComment,$content){
        if($authAccount->isDouyinCompany()){
            $url = self::DOUYIN_URL_COMMENT_REPLY_COMPANY;
        }else{
            $url = self::DOUYIN_URL_COMMENT_REPLY_COMMON;
        }
        $content = DouyinEmoji::inputContent($content);
        $query_arr = [
            'open_id'=>$authAccount->open_id,
            'access_token'=>$authAccount->token,
        ];
        $body_arr['item_id']=$authItem->item_id;
        $body_arr['content']=$content;
//        $authComment = $authComment->parentComment?:$authComment;
        if(!empty($authComment)){
            $body_arr['comment_id']=$authComment->comment_id;
        }
//        print_r($body_arr);exit;
        $body = json_encode($body_arr,JSON_UNESCAPED_UNICODE);
        $response = Func::postData(
            $url.'?'.http_build_query($query_arr),
            $body,5,
            ['Content-Type:application/json','Accept:application/json']);
        $result = self::checkResponse($response);
        $obj = new AuthComment();
        $obj->auth_app_id = $this->id;
        $obj->auth_account_id = $authAccount->id;
        $obj->auth_item_id = $authItem->id;
        $obj->auth_uid = $authAccount->app_uid;
        $obj->parent_id = $authComment->id;
        $obj->comment_id = $result['comment_id'];
        $obj->content = $content;
        $obj->create_time = time();
        $obj->post_time = time();
        if(!$obj->save()){
            throw new \Exception(json_encode($obj->getErrors()));
        }
        return $result;
    }
    //删除发布的视频
    public function authItemDelete(AuthAccount $authAccount,AuthItem $authItem){
        $query_arr = [
            'open_id'=>$authAccount->open_id,
            'access_token'=>$authAccount->token,
        ];
        $body = json_encode([
            'item_id'=>$authItem->item_id,
        ],JSON_UNESCAPED_UNICODE);

        $response = Func::postData(
            self::URL_VIDEO_DEL.'?'.http_build_query($query_arr),
            $body,5,
            ['Content-Type:application/json','Accept:application/json']);
        $data = self::checkResponse($response);
        return $authItem->item_id;
        throw new \Exception('本平台暂不支持删除',1);
    }
    //发布
    public function publishItem(AuthAccount $authAccount,AuthItem $authItem){
        //大于6M用分片上传,否则用普通上传
        if($authItem->video->size > 6000000){
            $data = $this->uploadPart($authAccount,$authItem);
        }else{
            $data = $this->upload($authAccount,$authItem);
        }
        $video_id = $data['video']['video_id'];
        $query_arr = [
            'open_id'=>$authAccount->open_id,
            'access_token'=>$authAccount->token,
        ];
        $body = json_encode(['video_id'=>$video_id,'text'=>$authItem->title],JSON_UNESCAPED_UNICODE);

        $response = Func::postData(
            self::URL_VIDEO_CREATE.'?'.http_build_query($query_arr),
            $body,5,
            ['Content-Type:application/json','Accept:application/json']);
        $data = self::checkResponse($response);
        return $data['item_id'];
    }
    //普通上传
    private function upload(AuthAccount $authAccount,AuthItem $authItem){
        $video = $authItem->video;
        $query_arr = [
            'open_id'=>$authAccount->open_id,
            'access_token'=>$authAccount->token,
        ];
        $content=$video->getPartData(0,6000000);
        $body_arr = Func::buildDouyinUploadData($content);


        $response = Func::postUploadData(
            self::URL_VIDEO_UPLOAD.'?'.http_build_query($query_arr),
            $body_arr['data'],0,
            ['Content-Type:multipart/form-data;boundary='.$body_arr['boundary']]);
        $data = self::checkResponse($response);
        print_r($response);
        return $data;

    }
    //分片上传
    private function uploadPart(AuthAccount $authAccount,AuthItem $authItem){
        $video = $authItem->video;
        $query_arr = [
            'open_id'=>$authAccount->open_id,
            'access_token'=>$authAccount->token,
        ];
        $body = '';

        $response = Func::postUploadData(
            self::URL_VIDEO_UPLOAD_PART_INIT.'?'.http_build_query($query_arr),
            $body,5,
            ['Content-Type:application/json']);
        $data = self::checkResponse($response);
//        print_r($data);exit;
        $upload_id = $data['upload_id'];
        $part=1;
        $part_size = 6000000;
        while($part){
            $start = ($part-1)*$part_size;
            if($start>=$video->size){
                break;
            }

            //如果剩余不足一个分片则一并上传
            $yu = $video->size - $start - $part_size;
            if($yu < $part_size){
                $part_size += $yu;
            }
            $content=$video->getPartData($start,$part_size);
            $body_arr = Func::buildDouyinUploadData($content);

//            print_r($body_arr);exit;
            $query_arr = [
                'open_id'=>$authAccount->open_id,
                'access_token'=>$authAccount->token,
                'upload_id'=>$upload_id,
                'part_number'=>$part,
            ];
//            $body = 'video='.$content;

            $response = Func::postUploadData(
                self::URL_VIDEO_UPLOAD_PART_UPLOAD.'?'.http_build_query($query_arr),
                $body_arr['data'],0,
                [
                    'Content-Type:multipart/form-data;boundary='.$body_arr['boundary'],
                ]);
            $data2 = self::checkResponse($response);
            $part++;

        }
        $query_arr = [
            'open_id'=>$authAccount->open_id,
            'access_token'=>$authAccount->token,
            'upload_id'=>$upload_id,
        ];

        $response = Func::postData(
            self::URL_VIDEO_UPLOAD_PART_COMPLETE.'?'.http_build_query($query_arr),
            $body,0,
            ['Content-Type:multipart/form-data']);
        $data = self::checkResponse($response);
        return $data;
    }
    //同步项目评论
    public function syncComments(AuthAccount $authAccount,AuthItem $authItem){
        $cursor=0;
        $count = 20;
        if($authAccount->isDouyinCompany()){
            $url = self::DOUYIN_URL_COMMENT_LIST_COMPANY;
            $url_reply = self::DOUYIN_URL_COMMENT_REPLY_LIST_COMPANY;
        }else{
            $url = self::DOUYIN_URL_COMMENT_LIST_COMMON;
            $url_reply = self::DOUYIN_URL_COMMENT_REPLY_LIST_COMMON;
        }
        //同步评论
        $query_arr = [
            'open_id'=>$authAccount->open_id,
            'access_token'=>$authAccount->token,
            'item_id'=>$authItem->item_id,
            'count'=>$count,
            'cursor'=>$cursor,
        ];
//        print_r($query_arr);exit;
        $cols = ['auth_app_id','auth_account_id','auth_item_id','auth_uid','comment_id','content','is_top','digg_count','reply_count','post_time','create_time'];
        do{
            $response = Func::file_get_contents($url.'?'.http_build_query($query_arr));
            $data = self::checkResponse($response);
            $open_ids = [];
            $auth_user_rows = [];
            $rows = [];
//            print_r($data);exit;
            if(!isset($data['list'])){
                break;
            }
            foreach ($data['list'] as $arr) {
                $open_ids[] = $arr['comment_user_id'];
                $auth_user_rows[]=[$this->id,$authAccount->id,$arr['comment_user_id'],time(),];
            }
            $sql = Yii::$app->db->getQueryBuilder()->batchInsert(AuthUser::tableName(), ['auth_app_id','auth_account_id','open_id','utime'], $auth_user_rows);
            $sql = str_replace('INSERT INTO','INSERT IGNORE INTO',$sql);
//            echo $sql;exit;
            Yii::$app->db->createCommand($sql)->execute();
            $auth_user_arr = AuthUser::find()->select(['open_id','id'])->where(['open_id'=>$open_ids])->indexBy('open_id')->asArray()->all();
//            print_r($auth_user_arr);exit;
            foreach ($data['list'] as $arr) {
                $rows[] = [
                    $this->id,
                    $authAccount->id,
                    $authItem->id,
                    $auth_user_arr[$arr['comment_user_id']]['id'],
                    $arr['comment_id'],
                    $arr['content'],
                    intval($arr['top']),
                    intval($arr['digg_count']),
                    intval($arr['reply_comment_total']),
                    intval($arr['create_time']),
                    time(),
                ];
            }
            $sql = Yii::$app->db->getQueryBuilder()->batchInsert(AuthComment::tableName(), $cols, $rows);
            $sql .= '  ON DUPLICATE KEY UPDATE 
                auth_uid=VALUES(auth_uid),
                is_top=VALUES(is_top),
                digg_count=VALUES(digg_count),
                reply_count=VALUES(reply_count)
            ';
            Yii::$app->db->createCommand($sql)->execute();

            $query_arr['cursor']=$data['cursor'];

        }while($data['has_more']);
        $query = AuthComment::find()->where(['auth_item_id'=>$authItem->id])->andWhere(['>','reply_count',0]);
        $comments = $query->all();
        foreach($comments as $comment){
            self::syncCommentReply($authAccount,$authItem,$comment);
        }

    }
    //更新项目评论的回复
    public function syncCommentReply(AuthAccount $authAccount,AuthItem $authItem,AuthComment $authComment){
        $cursor=0;
        $count = 20;
        if($authAccount->isDouyinCompany()){
            $url = self::DOUYIN_URL_COMMENT_REPLY_LIST_COMPANY;
        }else{
            $url = self::DOUYIN_URL_COMMENT_REPLY_LIST_COMMON;
        }
      //同步
        $query_arr = [
            'open_id'=>$authAccount->open_id,
            'access_token'=>$authAccount->token,
            'item_id'=>$authItem->item_id,
            'count'=>$count,
            'cursor'=>$cursor,
            'comment_id'=>$authComment->comment_id,
        ];
        $cols = ['auth_app_id','auth_account_id','auth_item_id','auth_uid','parent_id','comment_id','content','is_top','digg_count','reply_count','post_time','create_time'];
        do{
            $response = Func::file_get_contents($url.'?'.http_build_query($query_arr));
            $data = self::checkResponse($response);
            $open_ids = [];
            $auth_user_rows = [];
            $rows = [];
//            print_r($data['list']);exit;
            foreach ($data['list'] as $arr) {
                $open_ids[] = $arr['comment_user_id'];
                $auth_user_rows[]=[$this->id,$authAccount->id,$arr['comment_user_id'],time(),];
            }
            $sql = Yii::$app->db->getQueryBuilder()->batchInsert(AuthUser::tableName(), ['auth_app_id','auth_account_id','open_id','utime'], $auth_user_rows);
            $sql = str_replace('INSERT INTO','INSERT IGNORE INTO',$sql);
//            echo $sql;exit;
            Yii::$app->db->createCommand($sql)->execute();
            $auth_user_arr = AuthUser::find()->select(['open_id','id'])->where(['open_id'=>$open_ids])->indexBy('open_id')->asArray()->all();
//            print_r($auth_user_arr);exit;
            foreach ($data['list'] as $arr) {
                $rows[] = [
                    $this->id,
                    $authAccount->id,
                    $authItem->id,
                    $auth_user_arr[$arr['comment_user_id']]['id'],
                    $authComment->id,
                    $arr['comment_id'],
                    $arr['content'],
                    intval($arr['top']),
                    intval($arr['digg_count']),
                    intval($arr['reply_comment_total']),
                    intval($arr['create_time']),
                    time(),
                ];
            }
            $sql = Yii::$app->db->getQueryBuilder()->batchInsert(AuthComment::tableName(), $cols, $rows);
            $sql .= '  ON DUPLICATE KEY UPDATE 
                auth_uid=VALUES(auth_uid),
                parent_id=VALUES(parent_id),
                is_top=VALUES(is_top),
                digg_count=VALUES(digg_count),
                reply_count=VALUES(reply_count)
            ';
            Yii::$app->db->createCommand($sql)->execute();

            $query_arr['cursor']=$data['cursor'];

        }while($data['has_more']);
    }

    //同步单个发布项目
    public function syncItem(AuthAccount $authAccount, AuthItem $authItem){
        $query_arr = [
            'open_id'=>$authAccount->open_id,
            'access_token'=>$authAccount->token,
        ];
        $body = json_encode(['item_ids'=>[$authItem->item_id]],JSON_UNESCAPED_UNICODE);

        $response = Func::postData(
            self::URL_VIDEO_DATA.'?'.http_build_query($query_arr),
            $body,5,
            ['Content-Type:application/json','Accept:application/json']);
        $data = self::checkResponse($response);
        //抖音接口不报错，但是没数据，应该是在云端被删除了
        if(!isset($data['list'])){
            $authItem->state = $authItem::STATE_UNKNOW;
            $authItem->save();
            return true;
        }
        foreach($data['list'] as $arr){
            $authItem->title = $arr['title'];
            $authItem->cover = $arr['cover'];
            $authItem->show_url = $arr['share_url'];
            $authItem->is_top = intval($arr['is_top']);
            $authItem->comment_count = $arr['statistics']['comment_count']??0;
            $authItem->digg_count = $arr['statistics']['digg_count']??0;
            $authItem->download_count = $arr['statistics']['download_count']??0;
            $authItem->play_count = $arr['statistics']['play_count']??0;
            $authItem->share_count = $arr['statistics']['share_count']??0;
            $authItem->forward_count = $arr['statistics']['forward_count']??0;
            $authItem->post_time = $arr['create_time'];
            $authItem->state = self::$rel_item_state[$arr['video_status']]??AuthItem::STATE_UNKNOW;
            if(!$authItem->save()){
                throw new \Exception(json_encode($authItem->getErrors(),JSON_UNESCAPED_UNICODE));
            }

        }
        return true;

    }
    //同步用户发布的项目
    public function syncItems(AuthAccount $authAccount){
        $cursor=0;
        $count = 10;
        $cols = ['auth_app_id','auth_account_id','item_id','title','cover','show_url','is_top','comment_count','digg_count','download_count','play_count','share_count','forward_count','post_time','create_time','state'];
        $rows = [];

        $query_arr = [
            'open_id'=>$authAccount->open_id,
            'access_token'=>$authAccount->token,
            'count'=>$count,
            'cursor'=>$cursor,
        ];
        do{
            $response = Func::file_get_contents(self::URL_VIDEO_LIST.'?'.http_build_query($query_arr));
            $data = self::checkResponse($response);
            if(!isset($data['list'])){
                break;
            }
            foreach ($data['list'] as $arr) {
                $rows[] = [
                    $this->id,
                    $authAccount->id,
                    $arr['item_id'],
                    $arr['title'],
                    $arr['cover'],
                    $arr['share_url'],
                    $arr['is_top']?1:0,
                    $arr['statistics']['comment_count']??0,
                    $arr['statistics']['digg_count']??0,
                    $arr['statistics']['download_count']??0,
                    $arr['statistics']['play_count']??0,
                    $arr['statistics']['share_count']??0,
                    $arr['statistics']['forward_count']??0,
                    $arr['create_time'],
                    $arr['create_time'],
                    self::$rel_item_state[$arr['video_status']]??6,
                ];
            }
            $query_arr['cursor']=$data['cursor'];

        }while($data['has_more']);
        if(empty($rows)) return ;
//        print_r($rows);
        $sql = Yii::$app->db->getQueryBuilder()->batchInsert(AuthItem::tableName(), $cols, $rows);
        $sql .= '  ON DUPLICATE KEY UPDATE 
                cover=VALUES(cover),
                is_top=VALUES(is_top),
                comment_count=VALUES(comment_count),
                digg_count=VALUES(digg_count),
                download_count=VALUES(download_count),
                play_count=VALUES(play_count),
                share_count=VALUES(share_count),
                forward_count=VALUES(forward_count),
                state=VALUES(state)
            ';
//        echo $sql;exit;
        Yii::$app->db->createCommand($sql)->execute();

        return true;

    }
    //同步发布的数据
    public function syncItemsByIds(AuthAccount $authAccount, $item_ids=[]){
        $query_arr = [
            'open_id'=>$authAccount->open_id,
            'access_token'=>$authAccount->token,
        ];
        $body = json_encode(['item_ids'=>$item_ids],JSON_UNESCAPED_UNICODE);

        $response = Func::postData(
            self::URL_VIDEO_DATA.'?'.http_build_query($query_arr),
            $body,5,
            ['Content-Type:application/json','Accept:application/json']);
        $data = self::checkResponse($response);
        $cols = ['auth_app_id','auth_account_id','item_id','title','cover','show_url','is_top','comment_count','digg_count','download_count','play_count','share_count','forward_count','post_time','create_time','state'];
        $rows = [];
//            print_r($data);exit;
        if(!isset($data['list'])){
            return;
        }
        foreach ($data['list'] as $arr) {
            $rows[] = [
                $this->id,
                $authAccount->id,
                $arr['item_id'],
                $arr['title'],
                $arr['cover'],
                $arr['show_url'],
                $arr['is_top']?1:0,
                $arr['statistics']['comment_count']??0,
                $arr['statistics']['digg_count']??0,
                $arr['statistics']['download_count']??0,
                $arr['statistics']['play_count']??0,
                $arr['statistics']['share_count']??0,
                $arr['statistics']['forward_count']??0,
                $arr['create_time'],
                $arr['create_time'],
                self::$rel_item_state[$arr['video_status']]??6,
            ];
        }
        $sql = Yii::$app->db->getQueryBuilder()->batchInsert(AuthItem::tableName(), $cols, $rows);
        $sql .= '  ON DUPLICATE KEY UPDATE 
                cover=VALUES(cover),
                is_top=VALUES(is_top),
                comment_count=VALUES(comment_count),
                digg_count=VALUES(digg_count),
                download_count=VALUES(download_count),
                play_count=VALUES(play_count),
                share_count=VALUES(share_count),
                forward_count=VALUES(forward_count),
                state=VALUES(state)
            ';
        Yii::$app->db->createCommand($sql)->execute();

        return true;
    }
    //同步粉丝列表
    public function syncUserFans(AuthAccount $authAccount){
        $cursor=0;
        $count = 20;
        $query_arr = [
            'open_id'=>$authAccount->open_id,
            'access_token'=>$authAccount->token,
            'count'=>$count,
            'cursor'=>$cursor,
        ];
        $cols = ['auth_app_id','auth_account_id','open_id','union_id','nickname','avatar','gender','city','province','country','utime'];
        do{
            $response = Func::file_get_contents(self::URL_USER_FANS_LIST.'?'.http_build_query($query_arr));
            $data = self::checkResponse($response);
            $open_ids = [];
            $rows = [];
            foreach ($data['list'] as $arr) {
                $open_ids[] = $arr['open_id'];
                $rows[] = [
                    $this->id,
                    $authAccount->id,
                    $arr['open_id'],
                    $arr['union_id'],
                    $arr['nickname'],
                    $arr['avatar'],
                    $arr['gender'],
                    $arr['city'],
                    $arr['province'],
                    $arr['country'],
                    time(),
                ];
            }
            $sql = Yii::$app->db->getQueryBuilder()->batchInsert(AuthUser::tableName(), $cols, $rows);
            $sql .= '  ON DUPLICATE KEY UPDATE 
                nickname=VALUES(nickname),
                avatar=VALUES(avatar)
            ';
            Yii::$app->db->createCommand($sql)->execute();
            $users = AuthUser::find()->select(['NAME_CONST("uid",'.$authAccount->app_uid.')','id',])->where(['open_id'=>$open_ids])->asArray()->all();
            $sql = Yii::$app->db->getQueryBuilder()->batchInsert(AuthUserFans::tableName(), ['auth_uid','fans_uid'], $users);
            $sql = str_replace('INSERT INTO','INSERT IGNORE INTO',$sql);
            Yii::$app->db->createCommand($sql)->execute();

            $query_arr['cursor']=$data['cursor'];

        }while($data['has_more']);

    }
    //同步关注列表
    public function syncUserFollows(AuthAccount $authAccount){
        $cursor=0;
        $count = 20;
        $query_arr = [
            'open_id'=>$authAccount->open_id,
            'access_token'=>$authAccount->token,
            'count'=>$count,
            'cursor'=>$cursor,
        ];
        $cols = ['auth_app_id','auth_account_id','open_id','union_id','nickname','avatar','gender','city','province','country','utime'];
        do{
            $response = Func::file_get_contents(self::URL_USER_FOLLOW_LIST.'?'.http_build_query($query_arr));
            $data = self::checkResponse($response);
            $open_ids = [];
            $rows = [];
            foreach ($data['list'] as $arr) {
                $open_ids[] = $arr['open_id'];
                $rows[] = [
                    $this->id,
                    $authAccount->id,
                    $arr['open_id'],
                    $arr['union_id'],
                    $arr['nickname'],
                    $arr['avatar'],
                    $arr['gender'],
                    $arr['city'],
                    $arr['province'],
                    $arr['country'],
                    time(),
                ];
            }
            $sql = Yii::$app->db->getQueryBuilder()->batchInsert(AuthUser::tableName(), $cols, $rows);
            $sql .= '  ON DUPLICATE KEY UPDATE 
                nickname=VALUES(nickname),
                avatar=VALUES(avatar)
            ';
            Yii::$app->db->createCommand($sql)->execute();
            $users = AuthUser::find()->select(['id','NAME_CONST("uid",'.$authAccount->app_uid.')'])->where(['open_id'=>$open_ids])->asArray()->all();
            $sql = Yii::$app->db->getQueryBuilder()->batchInsert(AuthUserFans::tableName(), ['auth_uid','fans_uid'], $users);
            $sql = str_replace('INSERT INTO','INSERT IGNORE INTO',$sql);
            Yii::$app->db->createCommand($sql)->execute();

            $query_arr['cursor']=$data['cursor'];

        }while($data['has_more']);

    }
    //更新用户信息
    public function updateAuthUserInfo(AuthAccount $obj,AuthUser $authUser){
        $arr = [
            'access_token'=>$obj->token,
            'open_id'=>$authUser->open_id,
        ];
        $response = Func::file_get_contents(self::URL_USER_INFO.'?'.http_build_query($arr));
        print_r($response);
        $data = self::checkResponse($response);
        $authUser->union_id = $data['union_id'];
        $authUser->avatar = $data['avatar'];
        $authUser->nickname = $data['nickname'];
        $authUser->gender = $data['gender'];
        $authUser->city = $data['city'];
        $authUser->province = $data['province'];
        $authUser->country = $data['country'];
        $authUser->role = self::$roles[$data['e_account_role']]??0;
        if(!$authUser->save()){
            throw new \Exception(json_encode($authUser->getErrors(),JSON_UNESCAPED_UNICODE));
        }

        return $authUser;
    }
    //更新授权账户信息
    public function updateAuthAccountInfo(AuthAccount $authAccount){
        $arr = [
            'access_token'=>$authAccount->token,
            'open_id'=>$authAccount->open_id,
        ];
        $response = Func::file_get_contents(self::URL_USER_INFO.'?'.http_build_query($arr));
//        print_r($response);
        $data = self::checkResponse($response);
        $authAccount->avatar = $data['avatar'];
        $authAccount->nickname = $data['nickname'];
        if(!$authAccount->save()){
            throw new \Exception(json_encode($authAccount->getErrors(),JSON_UNESCAPED_UNICODE));
        }

        return $authAccount;
    }
    public function getAuthUserInfo(AuthAccount $obj){
        $arr = [
            'access_token'=>$obj->token,
            'open_id'=>$obj->open_id,
        ];
        $response = file_get_contents(self::URL_USER_INFO.'?'.http_build_query($arr));
        print_r($response);
        $data = self::checkResponse($response);
        return $data;
    }
    //同步达人榜
    public function syncStatUserItem(AuthAccount $authAccount){
        $arr = [
            'access_token'=>$authAccount->token,
            'open_id'=>$authAccount->open_id,
            'date_type'=>7,
        ];
        $response = file_get_contents(self::URL_DATA_USER_ITEM.'?'.http_build_query($arr));
        print_r($response);
        $data = self::checkResponse($response);
        print_r($data);
        return $data;
    }
    //同步达人榜
    public function syncStarTop($type){
        $query_arr = [
            'access_token'=>$this->getClientToken(),
            'hot_list_type'=>$type,
        ];
        $cols = ['type','unique_id','nick_name','follower','rank','score','tags'];
        $response = Func::file_get_contents(self::URL_STAR_TOP.'?'.http_build_query($query_arr));
        $data = self::checkResponse($response);
        if(!isset($data['list'])) return;
//        print_r($data);exit;
        $rows = [];
        foreach ($data['list'] as $arr) {
            $rows[] = [
                $type,
                $arr['unique_id'],
                $arr['nick_name'],
                $arr['follower'],
                $arr['rank'],
                $arr['score'],
                isset($arr['tags'])?implode(' ',$arr['tags']):'无',
            ];
        }
        $sql = Yii::$app->db->getQueryBuilder()->batchInsert(DouyinStarTop::tableName(), $cols, $rows);
        Yii::$app->db->createCommand($sql)->execute();
    }
    //同步达人指数数据
    public function syncStarInfo($unique_id){
        $query_arr = [
            'access_token'=>$this->getClientToken(),
            'unique_id'=>$unique_id,
        ];
        $cols = ['unique_id','nick_name','shop_score','star_score','cooperation_score','cp_score','growth_score','spread_score','update_timestamp'];
        $response = Func::file_get_contents(self::URL_STAR_INFO.'?'.http_build_query($query_arr));
        $data = self::checkResponse($response);
        if(empty($data)) return;
        $arr = $data;
        $rows[] = [
            $unique_id,
            $arr['nick_name'],
            $arr['shop_score'],
            $arr['star_score'],
            $arr['cooperation_score'],
            $arr['cp_score'],
            $arr['growth_score'],
            $arr['spread_score'],
            $arr['update_timestamp'],
        ];
        $sql = Yii::$app->db->getQueryBuilder()->batchInsert(DouyinStarInfo::tableName(), $cols, $rows);
        $sql .= '  ON DUPLICATE KEY UPDATE 
                shop_score=VALUES(shop_score),
                star_score=VALUES(star_score)
            ';
        Yii::$app->db->createCommand($sql)->execute();
    }
    //同步热点词
    public function syncHotWord(){
        $query_arr = [
            'access_token'=>$this->getClientToken(),
        ];
        $cols = ['type','sentence','hot_level','label'];
        $response = Func::file_get_contents(self::URL_HOT_WORD.'?'.http_build_query($query_arr));
        $data = self::checkResponse($response);
        if(!isset($data['list'])) return;
//        print_r($data);
        $rows = [];
        foreach ($data['list'] as $arr) {
            $rows[] = [
                1,
                $arr['sentence'],
                $arr['hot_level'],
                0,
            ];
        }
        $sql = Yii::$app->db->getQueryBuilder()->batchInsert(DouyinHot::tableName(), $cols, $rows);
        Yii::$app->db->createCommand($sql)->execute();
    }
    //同步上升词
    public function syncUpWord(){
        $cursor=0;
        $count = 20;
        $query_arr = [
            'access_token'=>$this->getClientToken(),
            'count'=>$count,
            'cursor'=>$cursor,
        ];
        $cols = ['type','sentence','hot_level','label'];
        while(1){
            $response = Func::file_get_contents(self::URL_UP_WORD.'?'.http_build_query($query_arr));
            $data = self::checkResponse($response);
            if(!isset($data['list'])) break;
            $rows = [];
            foreach ($data['list'] as $arr) {
                $rows[] = [
                    2,
                    $arr['sentence'],
                    $arr['hot_level'],
                    $arr['label'],
                ];
            }
            $sql = Yii::$app->db->getQueryBuilder()->batchInsert(DouyinHot::tableName(), $cols, $rows);
            Yii::$app->db->createCommand($sql)->execute();
            $query_arr['cursor']=$data['cursor'];
            if(!$data['has_more']) break;
        }
    }
    //同步影视综榜单版本列表
    public function syncRankObjs(DouyinRank $douyinRank){
        $query_arr = [
            'access_token'=>$this->getClientToken(),
            'type'=>$douyinRank->type,
            'version'=>$douyinRank->version,
        ];
        $cols = ['douyin_rank_id','type','maoyan_id','version','name','name_en','release_date','directors','discussion_hot','poster','tags','actors','areas','hot','search_hot','movie_id','influence_hot','topic_hot'];
        $response = Func::file_get_contents(self::URL_RANK_OBJS.'?'.http_build_query($query_arr));
        $data = self::checkResponse($response);
        if(!isset($data['list'])) return;
//        print_r($data);
        $rows = [];
        foreach ($data['list'] as $arr) {
            $rows[] = [
                $douyinRank->id,
                $douyinRank->type,
                $arr['maoyan_id'],
                $douyinRank->version,
                $arr['name'],
                $arr['name_en'],
                $arr['release_date'],
                isset($arr['directors'])?implode(' ',$arr['directors']):'',
                $arr['discussion_hot'],
                $arr['poster'],
                isset($arr['tags'])?implode(' ',$arr['tags']):'',
                isset($arr['actors'])?implode(' ',$arr['actors']):'',
                isset($arr['areas'])?implode(' ',$arr['areas']):'',
                $arr['hot'],
                $arr['search_hot'],
                $arr['id'],
                $arr['influence_hot'],
                $arr['topic_hot'],
            ];
        }
        $sql = Yii::$app->db->getQueryBuilder()->batchInsert(DouyinRankObj::tableName(), $cols, $rows);
//        $sql .= '  ON DUPLICATE KEY UPDATE
//                active_time=VALUES(active_time),
//                type=VALUES(type)
//            ';
        Yii::$app->db->createCommand($sql)->execute();

    }
    //同步影视综当前榜单
    public function syncRankObjsCurrent($type){
        $query_arr = [
            'access_token'=>$this->getClientToken(),
            'type'=>$type,
            'version'=>0,
        ];
        $cols = ['type','maoyan_id','name','name_en','release_date','directors','discussion_hot','poster','tags','actors','areas','hot','search_hot','movie_id','influence_hot','topic_hot'];
        $response = Func::file_get_contents(self::URL_RANK_OBJS.'?'.http_build_query($query_arr));
        $data = self::checkResponse($response);
        if(!isset($data['list'])) return;
//        print_r($data);
        $rows = [];
        foreach ($data['list'] as $arr) {
            $rows[] = [
                $type,
                $arr['maoyan_id'],
                $arr['name'],
                $arr['name_en'],
                $arr['release_date'],
                isset($arr['directors'])?implode(' ',$arr['directors']):'',
                $arr['discussion_hot'],
                $arr['poster'],
                isset($arr['tags'])?implode(' ',$arr['tags']):'',
                isset($arr['actors'])?implode(' ',$arr['actors']):'',
                isset($arr['areas'])?implode(' ',$arr['areas']):'',
                $arr['hot'],
                $arr['search_hot'],
                $arr['id'],
                $arr['influence_hot'],
                $arr['topic_hot'],
            ];
        }
        $sql = Yii::$app->db->getQueryBuilder()->batchInsert(DouyinRankObjCurrent::tableName(), $cols, $rows);
//        $sql .= '  ON DUPLICATE KEY UPDATE
//                active_time=VALUES(active_time),
//                type=VALUES(type)
//            ';
        Yii::$app->db->createCommand($sql)->execute();

    }
    //同步影视综榜单版本列表
    public function syncRankVersion($type = 1){
        $cursor=0;
        $count = 20;
        $query_arr = [
            'access_token'=>$this->getClientToken(),
            'count'=>$count,
            'cursor'=>$cursor,
            'type'=>$type,
        ];
        $cols = ['active_time','start_time','end_time','type','version'];
        while(1){
            $response = Func::file_get_contents(self::URL_RANK_VERSION.'?'.http_build_query($query_arr));
            $data = self::checkResponse($response);
            if(!isset($data['list'])) break;
            $rows = [];
            foreach ($data['list'] as $arr) {
                $rows[] = [
                    strtotime($arr['active_time']),
                    strtotime($arr['start_time']),
                    strtotime($arr['end_time']),
                    $type,
                    $arr['version'],
                ];
            }
            $sql = Yii::$app->db->getQueryBuilder()->batchInsert(DouyinRank::tableName(), $cols, $rows);
            $sql .= '  ON DUPLICATE KEY UPDATE 
                active_time=VALUES(active_time),
                type=VALUES(type)
            ';
            Yii::$app->db->createCommand($sql)->execute();
            $query_arr['cursor']=$data['cursor'];
            if(!$data['has_more']) break;
        }

    }

}
